package demo.java.parallelprogram.queue;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SyncThread implements  Runnable {

	private static int count;
	
	private static Lock lock=new ReentrantLock();
	
	public SyncThread(){
		count=0;
	}
	
	@Override
	public synchronized void run() {
		main();
	}
	
	public synchronized static void main(){
		for(int i=0;i<5;i++){
			try {
				System.out.println(Thread.currentThread().getName()+";=="+count++);
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	

	public static int getCount() {
		return count;
	}
	
	
	private Runnable createTask(){
		return new Runnable() {
			
			@Override
			public void run() {
				while(true){
					try {
						if(lock.tryLock(500,TimeUnit.MILLISECONDS)){
							try {
								System.out.println("locked"+Thread.currentThread().getName());
								Thread.sleep(1000);
							} finally {
								lock.unlock();
								System.out.println("unlocked "+Thread.currentThread());
							}
							
							break;
						}else{
							System.out.println("unable to lock "+Thread.currentThread().getName());
						}
					} catch (InterruptedException e) {
//						e.printStackTrace();
						System.out.println(Thread.currentThread().getName()+"is Interrupted");
					}
				}
			}
		};
	}
	
	
	public static void main1(String[] args) {
		Thread thread1 = new Thread(new SyncThread(), "SyncThread1");
		Thread thread2 = new Thread(new SyncThread(), "SyncThread2");
		thread1.start();
		thread2.start();
	}
	
	public static void main(String[] args) throws InterruptedException {
		Thread thread1 = new Thread(new SyncThread(), "SyncThread1");
		Thread thread2 = new Thread(new SyncThread(), "SyncThread2");
		thread1.start();
		thread2.start();
		Thread.sleep(600);
		thread2.interrupt();
	}
}
